<?php

require_once("dao/forecast.dao.php");
require_once("dao/placeFromSql.dao.php");
require_once("model/place.class.php");
require_once("model/route.class.php");
require_once("model/forecast.class.php");
//require_once("storage/predefRoutes.php");


class customRoute extends abstract_controller {

	function prepare_model($request_params, Smarty $smarty_obj) {
		$place= isset($_POST['place'])? ($_POST['place']): "";
		$dateIndex = isset($_POST['date']) ? htmlentities($_POST['date']) : null;
		$hour = isset($_POST['time']) ? htmlentities($_POST['time']) : null;

		$year  = date('Y');
		$month = date('m');
		$today = date('d');
		
		$dDate  = ''.$year.'-'.$month.'-'.$today.'';
		$date = new DateTime($dDate);
		if (is_null($dateIndex)){
			$hour  = date('H');
				
		//	$date  = $year.'-'.$month.'-'.$today;
		}else{
	//		$hour = $hour-2;
			$date = new DateTime($dDate);
	
			$date->modify("+ $dateIndex day");
		
			$setDate = $date->format("Y-m-d");
		}
		
		
		$xmlDate = $year.'-'.$month.'-'.$today.'T'.$hour.':00:00Z';
		
		
		
		$dateObj = functions::genereateDateObj($xmlDate);				 
		$smarty_obj->assign('page_title', 'TurYr: Velg rute');
		$smarty_obj->assign('date',$dateObj);

		if (isset($_GET['clear'])){
			session_destroy();
		} else if (isset($_SESSION['SCRoute'])){
			$route = unserialize($_SESSION['SCRoute']);			
		}
		
		if (!( empty($place) || empty($date) || is_null($hour) )){
			$nPlace = makePlace($place);
			$nPlace->setHour($hour);
			$nPlace->setDayIndex($dateIndex);
			
			$PName = $nPlace->getName();
			if(empty($PName)){
				$smarty_obj->assign('nonePlace', True);
			}else{
				$route = addPlace2Route($nPlace,$setDate);
			}
		}
		
		if (isset($route)){
			$smarty_obj->assign('route', $route);
		}
		
		if (!empty($date)){
			$smarty_obj->assign('ch_day', $date);
			$smarty_obj->assign('ch_time',$hour);
		} else {
			$smarty_obj->assign('ch_time','12');
		}	
	}

}

function addPlace2Route($newPlace,$xmlDate){
	if(isset($_SESSION["SCRoute"])){
		$route = unserialize($_SESSION["SCRoute"]);
		$route->setEndPlace($newPlace->getName());
	}else{
		$route = new RouteModel($newPlace->getName(),NULL,$xmlDate);
	}		
	
	$route->addPlace($newPlace,NULL,$xmlDate, true);
	
	$string = serialize($route);
	$_SESSION["SCRoute"] = $string;
	return $route;
}

function makePlace($place){
	return $newPlace = placeFromSql::findPlaceName($place);

}

?>
